﻿using EntityFrameworkSample.DB.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EntityFrameworkSample.DB
{
    public class DBInitializer : System.Data.Entity.CreateDatabaseIfNotExists<BlogContext>
    {
        protected override void Seed(BlogContext context)
        {
            context.Blogs.Add(new Blog { Name = "test" });
            context.SaveChanges();
            CreateTableValueTypes(context);
            InsertAssetTypesMapping(context);            
            base.Seed(context);
        }

        private void CreateTableValueTypes(BlogContext context)
        {
            context.Database.ExecuteSqlCommand(
                "if TYPE_ID(N'IntIdTableType') IS NULL CREATE TYPE dbo.IntIdTableType AS TABLE ( Id int)");
            context.Database.ExecuteSqlCommand(
                "if TYPE_ID(N'StrIdTableType') IS NULL CREATE TYPE dbo.StrIdTableType AS TABLE ( Id nvarchar(200))");
        }

        private static void InsertAssetTypesMapping(BlogContext context)
        {
            var insertAssetTypeSqlBuilder = new StringBuilder();
            Enum.GetNames(typeof(ContentTypeEnum)).Each(typeName =>
            {
                insertAssetTypeSqlBuilder.AppendFormat("INSERT INTO dbo.ContentType (ID, Name) VALUES ({0}, '{1}')",
                    (int)Enum.Parse(typeof(ContentTypeEnum), typeName),
                    typeName);
                insertAssetTypeSqlBuilder.AppendLine();
            });
            context.Database.ExecuteSqlCommand(insertAssetTypeSqlBuilder.ToString());
        }
    }
}
